from flask import Flask, render_template, request, send_from_directory
import requests
import hashlib
import random
import time
import json
import redis
from gevent import pywsgi

ser = Flask(__name__)
conn = redis.Redis()


# hello world! 完成
@ser.route('/')
def hello_world():
    val = conn.get('visitor_total').decode('utf-8')
    print('val:' + str(val))
    return render_template("index.html", input_text='', res_text='', people_number=val)


# get_txt 完成
@ser.route('/MP_verify_znm5jETdp0BTCwlj.txt')
def get_txt():
    return send_from_directory('', 'MP_verify_znm5jETdp0BTCwlj.txt')


# website_test 无用
@ser.route('/website/')
def get_website():
    return render_template("web_makedata.html", input_text='', res_text='')


# 处理token 完成
@ser.route('/token/')
def check_token():
    token = 'ComputeLight'
    # 接收到的是
    echostr = request.args.get('echostr')
    print("echostr:"+echostr)
    signature = request.args.get('signature')
    print("signature:"+signature)
    timestamp = request.args.get('timestamp')
    print("timestamp:"+timestamp)
    nonce = request.args.get('nonce')
    print("nonce:"+nonce)
    return echostr


# 记录人次的接口
@ser.route('/count/')
def count_test():
    print('begin')
    index = request.args.get('index')
    # 先处理总的访问人次
    if conn.get('visitor_total') is None:
        conn.set('visitor_total', 1)
        print(conn.get('visitor_total').decode('utf-8'))
    else:
        conn.incr('visitor_total')
        print(conn.get('visitor_total').decode('utf-8'))
    # 再处理各个图片的访问人次
    if conn.get(index) is None:
        conn.set(index, 1)
        print(conn.get(index).decode('utf-8'))
    else:
        conn.incr(index)
        print(conn.get(index).decode('utf-8'))
    dict_res = {}
    dict_res['visitor_total'] = conn.get('visitor_total').decode('utf-8')
    dict_res[index] = conn.get(index).decode('utf-8')
    print('visitor_total:' + str(conn.get('visitor_total')))
    print('index:' + str(index) + ' num:' + str(conn.get(index)))
    return dict_res


# 查看某个头像框使用的人次
@ser.route("/get_pics_times/<content>")
def get_pics_times(content):
    return conn.get(content).decode('utf-8')


# 查看总人次
@ser.route("/get_number_of_visitors/")
def get_number_of_visitors():
    return conn.get('visitor_total').decode('utf-8')


# 获取用户名和头像 已完成 未检验
@ser.route("/get_user_data/", methods=['POST'])
def get_user_data():
    print('get_user_data begin')
    code = request.form['code']
    print('code: ', code)
    url = request.form['url']
    print('url: ', url)
    # 合成获取access_token的url
    appid = 'wxf0b31034423882f6'
    secret = '7bfb45316c060c18faf09a62f834dd61'
    access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='
    access_token_url += appid
    access_token_url += '&secret='
    access_token_url += secret
    access_token_url += '&code='
    access_token_url += code
    access_token_url += '&grant_type=authorization_code'
    access_token_object = requests.get(url=access_token_url)
    print(access_token_object.text)
    dict_access_token = json.loads(access_token_object.text)
    try:
        # 扒出access_token的值
        access_token = dict_access_token['access_token']
    except Exception as e:
        # 如果获取access_token失败
        print('access_token获取失败')
        print(access_token_object.text)
        return access_token_object.text
    # 扒出openid的值
    openid = dict_access_token['openid']
    # 合成查询user_data的url
    user_data_url = "https://api.weixin.qq.com/sns/userinfo?access_token="
    user_data_url += access_token
    user_data_url += '&openid='
    user_data_url += openid
    user_data_url += '&lang=zh_CN'
    user_data_object = requests.get(url=user_data_url)
    print(user_data_object.text)
    dict_user_data = json.loads(user_data_object.text)
    try:
        # 扒出headimgurl的值
        head_img_url = dict_user_data['headimgurl']
    except Exception as e:
        # 如果获取user_data失败
        print('user_data获取失败')
        print(user_data_object.text)
        return user_data_object.text
    # 获取jsapi_ticket
    # 重新获取一个access_token_2，这个和之前那个不同
    # 合成url
    grant_type = "client_credential"
    appid_2 = "wxf0b31034423882f6"
    secret_2 = "7bfb45316c060c18faf09a62f834dd61"
    access_token_2_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="
    access_token_2_url += grant_type
    access_token_2_url += "&appid="
    access_token_2_url += appid_2
    access_token_2_url += "&secret="
    access_token_2_url += secret_2
    access_token_2_object = requests.get(url=access_token_2_url)
    print(access_token_2_object.text)
    dict_access_token_2 = json.loads(access_token_2_object.text)
    try:
        # 扒出access_token_2
        access_token_2 = dict_access_token_2['access_token']
    except Exception as e:
        # 如果失败
        print('access_token_2获取失败')
        print(access_token_2_object.text)
        return access_token_2_object.text
    # 用新的access_ticket来获取jsapi_ticket
    # 合成url
    jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
    jsapi_ticket_url += access_token_2
    jsapi_ticket_url += "&type=jsapi"
    jsapi_ticket_object = requests.get(url=jsapi_ticket_url)
    print(jsapi_ticket_object.text)
    dict_jsapi_ticket = json.loads(jsapi_ticket_object.text)
    try:
        # 扒出ticket
        jsapi_ticket = dict_jsapi_ticket['ticket']
    except Exception as e:
        # 如果获取jsapi_ticket_object失败
        print('jsapi_ticket获取失败')
        print(jsapi_ticket_object.text)
        return jsapi_ticket_object.text
    # 得到noncestr
    noncestr = get_noncestr(16)
    # 得到timestamp
    timestamp = str(int(time.time()))
    # 生成string1
    string1 = "jsapi_ticket=" + str(jsapi_ticket) + "&noncestr=" + str(noncestr) + "&timestamp=" + str(timestamp) + "&url=" + str(url)
    print(string1)
    # 生成signature
    sha1 = hashlib.sha1()
    sha1.update(string1.encode('utf8'))
    signature = sha1.hexdigest()
    dict_return = {}
    dict_return['headimgurl'] = head_img_url
    dict_return['timestamp'] = timestamp
    dict_return['noncestr'] = noncestr
    dict_return['signature'] = signature
    print('get_user_data成功！')
    return dict_return


# 获取随机字段 完成
def get_noncestr(randomlength):
    random_str = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    return random_str


# 获取get_user_data_test
# @ser.route('/get_user_data_test/<content>')
# def get_user_data_test(content):
#     def get_value(obt, title):
#         loc_1 = obt.find(title) + len(title) + 3
#         loc_2 = obt.find(",", loc_1, ) - 1
#         return obt[loc_1: loc_2]

@ser.route('/get_user_data_test', methods=['POST'])
def get_user_data_test():
    code = request.form['code']

    url = request.form["url"]  # post方法获取参数需要使用request.form
    

    # 获取jsapi_ticket
    # 重新获取一个access_token_2，这个和之前那个不同
    # 合成url
    grant_type = "client_credential"
    appid_2 = "wxf0b31034423882f6"
    secret_2 = "7bfb45316c060c18faf09a62f834dd61"
    access_token_2_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="
    access_token_2_url += grant_type
    access_token_2_url += "&appid="
    access_token_2_url += appid_2
    access_token_2_url += "&secret="
    access_token_2_url += secret_2
    access_token_2_object = requests.get(url=access_token_2_url)
    # 如果失败
    if access_token_2_object.text[2: 9] == "errcode":
        print('测试失败')
        return access_token_2_object.text + "\naccess_token_2 error"
    # 扒出access_token_2
    access_token_2 = get_value(access_token_2_object.text, "access_token")
    # 用新的access_ticket来获取jsapi_ticket
    # 合成url
    jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
    jsapi_ticket_url += access_token_2
    jsapi_ticket_url += "&type=jsapi"
    jsapi_ticket_object = requests.get(url=jsapi_ticket_url)
    # 如果获取jsapi_ticket_object失败
    # if jsapi_ticket_object.text[2: 9] == "errcode":
    #     print(jsapi_ticket_object.text)
    #     return jsapi_ticket_object.text + "\njsapi_ticket error"
    # 扒出ticket
    jsapi_ticket = get_value(jsapi_ticket_object.text, "ticket")
    # 得到noncestr
    noncestr = get_noncestr(16)
    # 得到timestamp
    timestamp = str(int(time.time()))
    # 生成string1
    string1 = "jsapi_ticket=" + str(jsapi_ticket) + "&noncestr=" + str(noncestr) + "&timestamp=" + str(timestamp) + "&url=" + str(url)
    # 生成signature
    sha1 = hashlib.sha1()
    sha1.update(string1.encode('utf8'))
    signature = sha1.hexdigest()
    tmp_dict = {}
    tmp_dict['timestamp'] = timestamp
    tmp_dict['noncestr'] = noncestr
    tmp_dict['signature'] = signature
    # print(tmp_dict)
    # print("url:"+str(url)) # 测试使用
    return tmp_dict

def get_value(obt, title):
    loc_1 = obt.find(title) + len(title) + 3
    loc_2 = obt.find(",", loc_1, ) - 1
    return obt[loc_1: loc_2]
def get_noncestr(randomlength):
    random_str = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    return random_str



if __name__ == '__main__':
    server = pywsgi.WSGIServer(('0.0.0.0', 80), ser)
    server.serve_forever()
